<?php

namespace App\Services\Store\Ranch;

use Exception;

class RanchService extends BaseRanchService
{

    /**
     * 牧场列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        // 总条数
        $total = $this->getStoreRanchModel()->total($params);
        // 查询牧场列表
        $ranchList = $this->getStoreRanchModel()->listByAdmin($params, [
            'store_ranch.id', 'store_user_id', 'name', 'province_id', 'city_id', 'region_id', 'address'
        ]);

        // 查询用户信息
        $userIds = array_column($ranchList, 'store_user_id');
        $userList = $this->getStoreUserModel()->getItemsByIds($userIds, [
            'id', 'phone', 'avatar', 'real_name',
        ]);
        $userListMap = array_column($userList, null, 'id');

        $provinceIds = array_column($ranchList, 'province_id');
        $cityIds = array_column($ranchList, 'city_id');
        $regionIds = array_column($ranchList, 'region_id');

        $areaIds = array_merge($provinceIds, $cityIds, $regionIds);

        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaListMap = array_column($areaList, 'name', 'code');

        $list = [];
        foreach ($ranchList as $item) {
            $areaName = $this->getAreaName($areaListMap[$item['province_id']], $areaListMap[$item['city_id']], $areaListMap[$item['region_id']]);

            $userInfo = [
                'id' => $userListMap[$item['store_user_id']]['id'],
                'phone' => $userListMap[$item['store_user_id']]['phone'],
                'avatar' => $userListMap[$item['store_user_id']]['avatar'],
                'realName' => $userListMap[$item['store_user_id']]['real_name'],
            ];

            $list[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'userInfo' => $userInfo,
                'areaName' => $areaName . ' ' . $item['address'],
            ];
        }

        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    /**
     * 已审核通过牧场列表
     * @return array
     * @throws Exception
     */
    public function passList(): array
    {
        // 查询牧场列表
        $ranchList = $this->getStoreRanchModel()->passList([
            'store_ranch.id', 'store_ranch.name'
        ]);

        $list = [];
        foreach ($ranchList as $item) {
            $list[] = [
                'id' => $item['id'],
                'name' => $item['name'],
            ];
        }

        return [
            'list' => $list,
        ];
    }
}
